package com.mofum.scope.common.utils;

import com.mofum.scope.common.model.Scope;
import com.mofum.scope.common.model.ScopeContext;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yuyang@qxy37.com
 * @since 2019-03-25
 **/
public class ScopeUtils {

    public static List<Scope> object2Scope(List<? extends Object> dataList, String column) throws IllegalAccessException {
        return object2Scope(dataList, column, false, false);
    }

    public static List<Scope> object2Scope(List<? extends Object> dataList, String column, boolean includeObjectClass, boolean saveOrigData) throws IllegalAccessException {

        List<Scope> scopes = new ArrayList<>();

        for (Object data : dataList) {

            if (data != null) {

                Field field = ParentFieldUtils.getFieldByName(column, data.getClass());

                if (field != null) {
                    Scope scope = new Scope();

                    field.setAccessible(true);
                    Object id = field.get(data);
                    field.setAccessible(false);

                    if (id == null) {
                        continue;
                    }

                    if (String.class.equals(id.getClass())) {
                        scope.setId((String) id);
                        if (saveOrigData) {
                            scope.setOrigData(data);
                        }
                    } else {
                        if (includeObjectClass) {
                            scope.setId(id.toString());
                            if (saveOrigData) {
                                scope.setOrigData(data);
                            }
                        }
                    }

                    scopes.add(scope);
                }

            }

        }

        return scopes;

    }


    public static ScopeContext<Map<String, Object>> convert2Context(HashMap<String, Object> parameters) {
        if (parameters == null) {
            return null;
        }
        ScopeContext<Map<String, Object>> scopeContext = new ScopeContext();
        scopeContext.setUsername(String.valueOf(parameters.get("username")));
        scopeContext.setPermission(String.valueOf(parameters.get("permission")));
        scopeContext.setContext(parameters);
        return scopeContext;
    }

}
